/* eslint-disable no-undef */
export const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1;
export const isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

//这是必须要写的，用来创建一些设置
function setupWebViewJavascriptBridge(callback) {
    //iOS使用
    if (isiOS) {
        if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
        if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
        window.WVJBCallbacks = [callback];
        let WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'https://__bridge_loaded__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
    }
    
    if (isAndroid) {
        //Android使用
        let bridge = window.WebViewJavascriptBridge || window.WKWebViewJavascriptBridge;
        if (bridge) { return callback(bridge); }
        let callbacks = window.WVJBCallbacks || window.WKWVJBCallbacks;
        if (callbacks) { return callbacks.push(callback); }
        window.WVJBCallbacks = window.WKWVJBCallbacks = [callback];
        if (window.WKWebViewJavascriptBridge) {
            //for https://github.com/Lision/WKWebViewJavascriptBridge
            window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null);
        } else {
            //for https://github.com/marcuswestin/WebViewJavascriptBridge
            let WVJBIframe = document.createElement('iframe');
            WVJBIframe.style.display = 'none';
            WVJBIframe.src = 'https://__bridge_loaded__';
            document.documentElement.appendChild(WVJBIframe);
            setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0);
        }
    }
}

//注册回调函数，第一次连接时调用 初始化函数(android需要初始化,ios不用)
// setupWebViewJavascriptBridge(function (bridge) {
    // if (isAndroid) {
    //     //初始化
    //     bridge.init(function (message, responseCallback) {
    //         var data = {
    //             'Javascript Responds': 'Wee!'
    //         };
    //         responseCallback(data);
    //     })
    // }
// })

export default {
    // js调APP方法 （参数分别为:app提供的方法名  传给app的数据  回调）
    callHandler: function (name, data, callback) {
        console.log(name, data);
        
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.callHandler(name, data, callback)
        })
    },
    
    // APP调js方法 （参数分别为:js提供的方法名  回调）
    registerHandler: function (name, callback) {
        setupWebViewJavascriptBridge(function (bridge) {
            bridge.registerHandler(name, function (data, responseCallback) {
                callback(data, responseCallback)
            })
        })
    }
}